home *** CD-ROM | disk | FTP | other *** search
/ SGI Freeware 1998 November / Freeware November 1998.img / dist / fw_emacs.idb / usr / freeware / info / ccmode-1.z / ccmode-1 (.txt)
GNU Info File  |  1998-10-27  |  47KB  |  906 lines

  1. This is Info file ../info/ccmode, produced by Makeinfo-1.63 from the
  2. input file cc-mode.texi.
  3.    Copyright (C) 1995 Free Software Foundation, Inc.
  4. File: ccmode,  Node: Top,  Next: Introduction,  Prev: (dir),  Up: (dir)
  5. * Menu:
  6. * Introduction::
  7. * Getting Connected::
  8. * New Indentation Engine::
  9. * Minor Modes::
  10. * Indentation Commands::
  11. * Customizing Indentation::
  12. * Syntactic Symbols::
  13. * Performance Issues::
  14. * Frequently Asked Questions::
  15. * Getting the latest cc-mode release::
  16. * Sample .emacs File::
  17. * Requirements::
  18. * Limitations and Known Bugs::
  19. * Mailing Lists and Submitting Bug Reports::
  20. * Concept Index::
  21. * Command Index::               Command Index
  22. * Key Index::                   Key Index
  23. * Variable Index::              Variable Index
  24. File: ccmode,  Node: Introduction,  Next: Getting Connected,  Prev: Top,  Up: Top
  25. Introduction
  26. ************
  27.    Welcome to `cc-mode', version 4.  This is a GNU Emacs mode for
  28. editing files containing C, C++, Objective-C, and Java code.  This
  29. incarnation of the mode is descendant from `c-mode.el' (also called
  30. "Boring Old C Mode" or BOCM `:-)', and `c++-mode.el' version 2, which I
  31. have been maintaining since 1992.  `cc-mode' represents a significant
  32. milestone in the mode's life.  It has been fully merged back with Emacs
  33. 19's `c-mode.el'. Also a new, more intuitive and flexible mechanism for
  34. controlling indentation has been developed.
  35.    `cc-mode' version 4 supports the editing of K&R and ANSI C, "ARM"
  36. (1) C++, Objective-C, and Java files.  In this way, you can easily set
  37. up consistent coding styles for use in editing all C, C++, Objective-C,
  38. and Java programs.
  39.    This manual will describe the following:
  40.    * How to get started using `cc-mode'.
  41.    * How the new indentation engine works.
  42.    * How to customize the new indentation engine.
  43.    Note that the name of this file is `cc-mode.el', and I'll often
  44. refer to the package as `cc-mode', but there really is no top level
  45. `cc-mode' entry point.  I call it `cc-mode' simply to differentiate it
  46. from `c-mode.el'.  All of the variables, commands, and functions in
  47. `cc-mode' are prefixed with `c-<thing>', and `c-mode', `c++-mode',
  48. `objc-mode', and `java-mode' entry points are provided.  This file is
  49. intended to be a replacement for `c-mode.el' and `c++-mode.el'.
  50.    The major version number was incremented to 4 with the addition of
  51. `objc-mode'. To find the minor revision number of this release, use
  52. `M-x c-version RET'.  Work has already begun on `cc-mode' version 5, in
  53. which Emacs 18 will not be supported.
  54.    As of this writing (19-Jan-1996), both Emacs 19.30 and XEmacs 19.13
  55. are distributed with `cc-mode'.  Emacs 19.31 and XEmacs 19.14 will both
  56. contain the latest version of cc-mode when it is released.  If you are
  57. running older versions of these Emacsen, you may want to upgrade your
  58. copy of `cc-mode'.  See *Note Getting the latest cc-mode release::.
  59.    This distribution also contains a file called `cc-compat.el' which
  60. should ease your transition from BOCM to `cc-mode'.  It currently comes
  61. unguaranteed and unsupported, but this may change for future versions.
  62.    A special word of thanks goes to Krishna Padmasola for his work in
  63. converting the original `README' file to texinfo format.  `cc-mode'
  64. users have been clamoring for a manual for a long time, and thanks to
  65. Krishna, it is now available <clap> <clap> <clap>!  `:-)'
  66.    ---------- Footnotes ----------
  67.    (1)  i.e. "The Annotated C++ Reference Manual", by Ellis and
  68. Stroustrup.
  69. File: ccmode,  Node: Getting Connected,  Next: New Indentation Engine,  Prev: Introduction,  Up: Top
  70. Getting Connected
  71. *****************
  72.    `cc-mode.el' works well with the 2 main branches of Emacs 19: XEmacs
  73. and the Emacs 19 maintained by the FSF.  Emacs 19 users will want to
  74. use Emacs version 19.21 or better, XEmacs users will want 19.6 or
  75. better.  Earlier versions of these Emacsen have deficiencies and/or bugs
  76. which will adversely affect the performance and usability of `cc-mode'.
  77.    Similarly if you use the `cc-mode-18.el' compatibility file,
  78. `cc-mode.el' will work with Emacs 18, but only moderately well.  A word
  79. of warning though, *Emacs 18 lacks some fundamental functionality and
  80. that ultimately means using Emacs 18 is a losing battle*.  Hence
  81. `cc-mode' under Emacs 18 is no longer supported and it is highly
  82. recommended that you upgrade to Emacs 19.  If you use `cc-mode' under
  83. Emacs 18, you're on your own.  With `cc-mode' version 5, Emacs 18
  84. support will be dropped altogether.
  85.    Note that as of XEmacs 19.13 and Emacs 19.30, your Emacs already
  86. comes with `cc-mode' version 4 preconfigured for your use.  You should
  87. be able to safely skip the rest of the setup information in this
  88. chapter.
  89.    The first thing you will want to do is put `cc-mode.el' somewhere on
  90. your `load-path' so Emacs can find it.  Do a `C-h v load-path RET' to
  91. see all the directories Emacs looks at when loading a file.  If none of
  92. these directories are appropriate, create a new directory and add it to
  93. your `load-path':
  94. *[in the shell]*
  95.      % cd
  96.      % mkdir mylisp
  97.      % mv cc-mode.el mylisp
  98.      % cd mylisp
  99. *[in your .emacs file add]*
  100.      (setq load-path (cons "~/mylisp" load-path))
  101.    Next you want to "byte compile" `cc-mode.el'.  The mode uses a lot
  102. of macros so if you don't byte compile it, things will be unbearably
  103. slow.  *You can ignore all byte-compiler warnings!*  They are the
  104. result of the supporting different versions of Emacs, and none of the
  105. warnings have any effect on operation. Let me say this again: *You
  106. really can ignore all byte-compiler warnings!*
  107.    Here's what to do to byte-compile the file [in emacs]:
  108.      M-x byte-compile-file RET ~/mylisp/cc-mode.el RET
  109.    If you are running a version of Emacs or XEmacs that comes with
  110. `cc-mode' by default, you can simply add the following to your `.emacs'
  111. file in order to upgrade to the latest version of `cc-mode':
  112.      (load "cc-mode")
  113.    Users of even older versions of Emacs 19, Emacs 18, or of the older
  114. Lucid Emacs will probably be running an Emacs that has BOCM `c-mode.el'
  115. and possible `c++-mode.el' pre-dumped.  If your Emacs is dumped with
  116. either of these files you first need to make Emacs "forget" about those
  117. older modes.
  118.    If you can do a `C-h v c-mode-map RET' without getting an error, you
  119. need to add these lines at the top of your `.emacs' file:
  120.      (fmakunbound 'c-mode)
  121.      (makunbound  'c-mode-map)
  122.      (fmakunbound 'c++-mode)
  123.      (makunbound  'c++-mode-map)
  124.      (makunbound  'c-style-alist)
  125.    After those lines you will want to add the following autoloads to
  126. your `.emacs' file so that `cc-mode' gets loaded at the right time:
  127.      (autoload 'c++-mode  "cc-mode" "C++ Editing Mode" t)
  128.      (autoload 'c-mode    "cc-mode" "C Editing Mode" t)
  129.      (autoload 'objc-mode "cc-mode" "Objective-C Editing Mode" t)
  130.      (autoload 'java-mode "cc-mode" "Java Editing Mode" t)
  131.    Alternatively, if you want to make sure `cc-mode' is loaded when
  132. Emacs starts up, you could use this line instead of the three autoloads
  133. above:
  134.      (require 'cc-mode)
  135.    Next, you will want to set up Emacs so that it edits C files in
  136. `c-mode', C++ files in `c++-mode', and Objective-C files in
  137. `objc-mode'. All users should add the following to their `.emacs' file.
  138. Note that this assumes you'll be editing `.h' and `.c' files as C,
  139. `.hh', `.cc', `.H', and `.C' files as C++, `.m' files as Objective-C,
  140. and `.java' files as Java code. YMMV:
  141.      (setq auto-mode-alist
  142.        (append
  143.          '(("\\.C$"    . c++-mode)
  144.            ("\\.H$"    . c++-mode)
  145.            ("\\.cc$"   . c++-mode)
  146.            ("\\.hh$"   . c++-mode)
  147.            ("\\.c$"    . c-mode)
  148.            ("\\.h$"    . c-mode)
  149.            ("\\.m$"    . objc-mode)
  150.            ("\\.java$" . java-mode)
  151.           ) auto-mode-alist))
  152.    You may already have some or all of these settings on your
  153. `auto-mode-alist', but it won't hurt to put them on there again.
  154.    That's all you need - I know, I know, it sounds like a lot `:-)',
  155. but after you've done all this, you should only need to quit and restart
  156. Emacs.  The next time you visit a C, C++, Objective-C, or Java file you
  157. should be using `cc-mode'.  You can check this easily by hitting `M-x
  158. c-version RET' in the `c-mode', `c++-mode', or `objc-mode' buffer.  You
  159. should see this message in the echo area:
  160.      Using `cc-mode' version 4.XXX
  161.      
  162.      Where XXX is the latest release minor number.
  163. * Menu:
  164. * Syntactic Analysis::
  165. * Indentation Calculation::
  166. File: ccmode,  Node: New Indentation Engine,  Next: Minor Modes,  Prev: Getting Connected,  Up: Top
  167. New Indentation Engine
  168. **********************
  169.    `cc-mode' has a new indentation engine, providing a simplified, yet
  170. flexible and general mechanism for customizing indentation. It breaks
  171. indentation calculation into two steps. First for the line of code being
  172. indented, `cc-mode' analyzes what kind of language construct it's
  173. looking at, then it applies user defined offsets to the current line
  174. based on this analysis.
  175.    This section will briefly cover how indentation is calculated in
  176. `cc-mode'. It is important to understand the indentation model being
  177. used so that you will know how to customize `cc-mode' for your personal
  178. coding style.
  179. * Menu:
  180. * Syntactic Analysis::
  181. * Indentation Calculation::
  182. File: ccmode,  Node: Syntactic Analysis,  Next: Indentation Calculation,  Up: New Indentation Engine
  183. Syntactic Analysis
  184. ==================
  185.    The first thing `cc-mode' does when indenting a line of code, is to
  186. analyze the line, determining the "syntactic component list" of the
  187. construct on that line.  A "syntactic component" consists of a pair of
  188. information (in lisp parlance, a *cons cell*), where the first part is
  189. a "syntactic symbol", and the second part is a "relative buffer
  190. position".  Syntactic symbols describe elements of C code (1), e.g.
  191. `statement', `substatement', `class-open', `class-close', etc.  *Note
  192. Syntactic Symbols::, for a complete list of currently recognized
  193. syntactic symbols and their semantics.  The variable `c-offsets-alist'
  194. also contains the list of currently supported syntactic symbols.
  195.    Conceptually, a line of C code is always indented relative to the
  196. indentation of some line higher up in the buffer.  This is represented
  197. by the relative buffer position in the syntactic component.
  198.    It might help to see an example. Suppose we had the following code as
  199. the only thing in a `c++-mode' buffer (2):
  200.        1: void swap( int& a, int& b )
  201.        2: {
  202.        3:     int tmp = a;
  203.        4:     a = b;
  204.        5:     b = tmp;
  205.        6: }
  206.    We can use the command `C-c C-s' (`c-show-syntactic-information') to
  207. simply report what the syntactic analysis is for the current line.
  208. Running this command on line 4 this example, we'd see in the echo area:
  209.      ((statement . 35))
  210.    This tells us that the line is a statement and it is indented
  211. relative to buffer position 35, which happens to be the `i' in `int' on
  212. line 3.  If you were to move point to line 3 and hit `C-c C-s', you
  213. would see:
  214.      ((defun-block-intro . 29))
  215.    This indicates that the `int' line is the first statement in a top
  216. level function block, and is indented relative to buffer position 29,
  217. which is the brace just after the function header.
  218.    Here's another example:
  219.        1: int add( int val, int incr, int doit )
  220.        2: {
  221.        3:     if( doit )
  222.        4:         {
  223.        5:             return( val + incr );
  224.        6:         }
  225.        7:     return( val );
  226.        8: }
  227. Hitting `C-c C-s' on line 4 gives us:
  228.      ((substatement-open . 46))
  229. which tells us that this is a brace that *opens* a substatement block.
  230.    Syntactic component lists can contain more than one component, and
  231. individual syntactic components need not have relative buffer positions.
  232. The most common example of this is a line that contains a "comment only
  233. line".
  234.        1: void draw_list( List<Drawables>& drawables )
  235.        2: {
  236.        3:         // call the virtual draw() method on each element in list
  237.        4:     for( int i=0; i < drawables.count(), ++i )
  238.        5:     {
  239.        6:         drawables[i].draw();
  240.        7:     }
  241.        8: }
  242. Hitting `C-c C-s' on line 3 of example 3 gives us:
  243.      ((comment-intro) (defun-block-intro . 46))
  244. so you can see that the syntactic component list contains two syntactic
  245. components.  Also notice that the first component, `(comment-intro)'
  246. has no relative buffer position.
  247.    ---------- Footnotes ----------
  248.    (1)  or C++, Objective-C, or Java code.  In general, for the rest of
  249. this manual I'll use the term "C code" to refer to all the C-like
  250. dialects, unless otherwise noted.
  251.    (2)  The line numbers in this and future examples don't actually
  252. appear in the buffer, of course!
  253.    (3)  A "substatement" indicates the line after an `if', `else',
  254. `while', `do', `switch', or `for' statement, and a "substatement block"
  255. is a brace block following one of those constructs.
  256. File: ccmode,  Node: Indentation Calculation,  Prev: Syntactic Analysis,  Up: New Indentation Engine
  257. Indentation Calculation
  258. =======================
  259.    Indentation for the current line is calculated using the syntactic
  260. component list derived in step 1 above (see *Note Syntactic Analysis::).
  261. Each component contributes to the final total indentation of the line in
  262. two ways.
  263.    First, the syntactic symbols are looked up in the `c-offsets-alist'
  264. variable, which is an association list of syntactic symbols and the
  265. offsets to apply for those symbols.  These offsets are added to the
  266. running total.
  267.    Second, if the component has a relative buffer position, `cc-mode'
  268. adds the column number of that position to the running total.  By adding
  269. up the offsets and columns for every syntactic component on the list,
  270. the final total indentation for the current line is computed.
  271.    Let's use our two code examples above to see how this works.  Here is
  272. our first example again:
  273.          1: void swap( int& a, int& b )
  274.          2: {
  275.          3:     int tmp = a;
  276.          4:     a = b;
  277.          5:     b = tmp;
  278.          6: }
  279.    Let's say point is on line 3 and we hit the TAB key to re-indent the
  280. line.  Remember that the syntactic component list for that line is:
  281.      ((defun-block-intro . 29))
  282. `cc-mode' looks up `defun-block-intro' in the `c-offsets-alist'
  283. variable.  Let's say it finds the value `4'; it adds this to the
  284. running total (initialized to zero), yielding a running total
  285. indentation of 4 spaces.
  286.    Next `cc-mode' goes to buffer position 29 and asks for the current
  287. column.  Since the brace at buffer position 29 is in column zero, it
  288. adds `0' to the running total.  Since there is only one syntactic
  289. component on the list for this line, indentation calculation is
  290. complete, and the total indentation for the line is 4 spaces.
  291.    Here's another example:
  292.          1: int add( int val, int incr, int doit )
  293.          2: {
  294.          3:     if( doit )
  295.          4:         {
  296.          5:             return( val + incr );
  297.          6:         }
  298.          7:     return( val );
  299.          8: }
  300.    If we were to hit `TAB' on line 4 in the above example, the same
  301. basic process is performed, despite the differences in the syntactic
  302. component list.  Remember that the list for this line is:
  303.      ((substatement-open . 46))
  304.    Here, `cc-mode' first looks up the `substatement-open' symbol in
  305. `c-offsets-alist'. Let's say it finds the value `4'.  This yields a
  306. running total of 4.  `cc-mode' then goes to buffer position 46, which
  307. is the `i' in `if' on line 3.  This character is in the fourth column
  308. on that line so adding this to the running total yields an indentation
  309. for the line of 8 spaces.
  310.    Simple, huh?
  311.    Actually, the mode usually just does The Right Thing without you
  312. having to think about it in this much detail.  But when customizing
  313. indentation, it's helpful to understand the general indentation model
  314. being used.
  315.    To help you configure `cc-mode', you can set the variable
  316. `c-echo-syntactic-information-p' to non-`nil' so that the syntactic
  317. component list and calculated offset will always be echoed in the
  318. minibuffer when you hit `TAB'.
  319. File: ccmode,  Node: Minor Modes,  Next: Indentation Commands,  Prev: New Indentation Engine,  Up: Top
  320. Minor Modes
  321. ***********
  322.    `cc-mode' contains two minor-mode-like features that you should find
  323. useful while you enter new C code.  The first is called "auto-newline"
  324. mode, and the second is called "hungry-delete" mode.  These minor modes
  325. can be toggled on and off independently, and `cc-mode' can be
  326. configured so that it comes up with any combination of these minor
  327. modes.  By default, both of these minor modes are turned off.
  328.    The state of the minor modes is always reflected in the minor mode
  329. list on the modeline of the `cc-mode' buffer.  When auto-newline mode is
  330. enabled, you will see `C/a' on the mode line (1).  When hungry delete
  331. mode is enabled you would see `C/h' and when both modes are enabled,
  332. you'd see `C/ah'.
  333.    `cc-mode' provides keybindings which allow you to toggle the minor
  334. modes while editing code on the fly.  To toggle just the auto-newline
  335. state, hit `C-c C-a' (`c-toggle-auto-state').  When you do this, you
  336. should see the `a' indicator either appear or disappear on the
  337. modeline.  Similarly, to toggle just the hungry-delete state, use `C-c
  338. C-d' (`c-toggle-hungry-state'), and to toggle both states together, use
  339. `C-c C-t' (`c-toggle-auto-hungry-state').
  340.    To set up the auto-newline and hungry-delete states to your preferred
  341. values, you would need to add some lisp to your `.emacs' file that
  342. called one of the `c-toggle-*-state' functions directly.  When called
  343. programmatically, each function takes a numeric value, where a positive
  344. number enables the minor mode, a negative number disables the mode, and
  345. zero toggles the current state of the mode.
  346.    So for example, if you wanted to enable both auto-newline and
  347. hungry-delete for all your C file editing, you could add the following
  348. to your `.emacs' file:
  349.      (add-hook 'c-mode-common-hook '(lambda () (c-toggle-auto-hungry-state 1)))
  350. * Menu:
  351. * Auto-newline insertion::
  352. * Hungry-deletion of whitespace::
  353.    ---------- Footnotes ----------
  354.    (1)  Remember that the `C' would be replaced with `C++' or `ObjC' if
  355. you were editing C++ or Objective-C code.
  356. File: ccmode,  Node: Auto-newline insertion,  Next: Hungry-deletion of whitespace,  Up: Minor Modes
  357. Auto-newline insertion
  358. ======================
  359.    Auto-newline minor mode works by enabling certain "electric
  360. commands".  Electric commands are typically bound to special characters
  361. such as the left and right braces, colons, semi-colons, etc., which when
  362. typed, perform some magic formatting in addition to inserting the typed
  363. character.  As a general rule, electric commands are only electric when
  364. the following conditions apply:
  365.    * Auto-newline minor mode is enabled, as evidenced by a `C/a' or
  366.      `C/ah' indicator on the modeline.
  367.    * The character was not typed inside of a literal (1).
  368.    * No numeric argument was supplied to the command (i.e. it was typed
  369.      as normal, with no `C-u' prefix).
  370.    Certain other conditions may apply on a language specific basis.  For
  371. example, the second slash (`/') of a C++ style line comment is electric
  372. in `c++-mode', `objc-mode', and `java-mode', but not in `c-mode'.
  373. * Menu:
  374. * Hanging Braces::
  375. * Hanging Colons::
  376. * Hanging Semi-colons and commas::
  377. * Other electric commands::
  378. * Clean-ups::
  379.    ---------- Footnotes ----------
  380.    (1)  A "literal" is defined in `cc-mode' as any comment, string, or
  381. cpp macro definition.  These constructs are also known as "syntactic
  382. whitespace" since they are usually ignored when scanning C code.
  383. File: ccmode,  Node: Hanging Braces,  Next: Hanging Colons,  Up: Auto-newline insertion
  384. Hanging Braces
  385. --------------
  386.    When you type either an open or close brace (i.e. `{' or `}'), the
  387. electric command `c-electric-brace' gets run.  This command has two
  388. electric formatting behaviors.  First, it will perform some
  389. re-indentation of the line the brace was typed on, and second, it will
  390. add various newlines before and/or after the typed brace.
  391. Re-indentation occurs automatically whenever the electric behavior is
  392. enabled.  If the brace ends up on a line other than the one it was typed
  393. on, then that line is on is also indented according to
  394. `c-offsets-alist'.
  395.    The insertion of newlines is controlled by the
  396. `c-hanging-braces-alist' variable.  This variable contains a mapping
  397. between syntactic symbols related to braces, and a list of places to
  398. insert a newline.  The syntactic symbols that are useful for this list
  399. are: `class-open', `class-close', `defun-open', `defun-close',
  400. `inline-open', `inline-close', `brace-list-open', `brace-list-close',
  401. `brace-list-intro', `brace-list-entry', `block-open', `block-close',
  402. `substatement-open', and `statement-case-open'.  *Note Syntactic
  403. Symbols:: for a more detailed description of these syntactic symbols.
  404.    The value associated with each syntactic symbol in this association
  405. list is called an ACTION which can be either a function or a list.
  406. *Note Custom Brace and Colon Hanging:: for a more detailed discussion of
  407. using a function as a brace hanging ACTION.
  408.    When ACTION is a list, it can contain any combination of the symbols
  409. `before' or `after', directing `cc-mode' where to put newlines in
  410. relationship to the brace being inserted.  Thus, if the list contains
  411. only the symbol `after', then the brace is said to "hang" on the right
  412. side of the line, as in:
  413.      // here, open braces always `hang'
  414.      void spam( int i ) {
  415.          if( i == 7 ) {
  416.              dosomething(i);
  417.          }
  418.      }
  419.    When the list contains both `after' and `before', the braces will
  420. appear on a line by themselves, as shown by the close braces in the
  421. above example.  The list can also be empty, in which case no newlines
  422. are added either before or after the brace.
  423.    For example, the default value of `c-hanging-braces-alist' is:
  424.      (defvar c-hanging-braces-alist '((brace-list-open)
  425.                                       (substatement-open after)
  426.                                       (block-close . c-snug-do-while)))
  427. which says that `brace-list-open' braces should both hang on the right
  428. side, and allow subsequent text to follow on the same line as the
  429. brace.  Also, `substatement-open' braces should hang on the right side,
  430. but subsequent text should follow on the next line.  Here, in the
  431. `block-close' entry, you also see an example of using a function as an
  432. ACTION.
  433. File: ccmode,  Node: Hanging Colons,  Next: Hanging Semi-colons and commas,  Prev: Hanging Braces,  Up: Auto-newline insertion
  434. Hanging Colons
  435. --------------
  436.    Using a mechanism similar to brace hanging (see *Note Hanging
  437. Braces::), colons can also be made to hang using the variable
  438. `c-hanging-colons-alist'.  The syntactic symbols appropriate for this
  439. association list are: `case-label', `label', `access-label',
  440. `member-init-intro', and `inher-intro'.  *Note Hanging Braces:: and
  441. *Note Custom Brace and Colon Hanging:: for details.  Note however, that
  442. `c-hanging-colons-alist' does not implement functions as ACTIONs.
  443.    In C++, double-colons are used as a scope operator but because these
  444. colons always appear right next to each other, newlines before and after
  445. them are controlled by a different mechanism, called "clean-ups" in
  446. `cc-mode'.  *Note Clean-ups:: for details.
  447. File: ccmode,  Node: Hanging Semi-colons and commas,  Next: Other electric commands,  Prev: Hanging Colons,  Up: Auto-newline insertion
  448. Hanging Semi-colons and commas
  449. ------------------------------
  450.    Semicolons and commas are also electric in `cc-mode', but since
  451. these characters do not correspond directly to syntactic symbols, a
  452. different mechanism is used to determine whether newlines should be
  453. automatically inserted after these characters.  *Note Customizing
  454. Semi-colons and Commas:: for details.
  455. File: ccmode,  Node: Other electric commands,  Next: Clean-ups,  Prev: Hanging Semi-colons and commas,  Up: Auto-newline insertion
  456. Other electric commands
  457. -----------------------
  458.    A few other keys also provide electric behavior.  For example the
  459. `#' key (`c-electric-pound') is electric when it is typed as the first
  460. non-whitespace character on a line.  In this case, the variable
  461. `c-electric-pound-behavior' is consulted for the electric behavior.
  462. This variable takes a list value, although the only element currently
  463. defined is `alignleft', which tells this command to force the `#'
  464. character into column zero.  This is useful for entering cpp macro
  465. definitions.
  466.    Stars and slashes (i.e. `*' and `/') are also electric under certain
  467. circumstances.  If a star is inserted as the second character of a C
  468. style block comment on a "comment-only" line, then the comment
  469. delimiter is indented as defined by `c-offsets-alist'.  A comment-only
  470. line is defined as a line which contains only a comment, as in:
  471.      void spam( int i )
  472.      {
  473.              // this is a comment-only line...
  474.          if( i == 7 )                             // but this is not
  475.          {
  476.              dosomething(i);
  477.          }
  478.      }
  479.    Likewise, if a slash is inserted as the second slash in a C++ style
  480. line comment (also only on a comment-only line), then the line is
  481. indented as defined by `c-offsets-alist'.
  482. File: ccmode,  Node: Clean-ups,  Prev: Other electric commands,  Up: Auto-newline insertion
  483. Clean-ups
  484. ---------
  485.    "Clean-ups" are a mechanism complementary to colon and brace
  486. hanging.  On the surface, it would seem that clean-ups overlap the
  487. functionality provided by the `c-hanging-*-alist' variables, and
  488. similarly, clean-ups are only enabled when auto-newline minor mode is
  489. enabled.  Clean-ups are used however to adjust code "after-the-fact",
  490. i.e. to eliminate some whitespace that isn't inserted by electric
  491. commands, or whitespace that contains intervening constructs.
  492.    You can configure `cc-mode''s clean-ups by setting the variable
  493. `c-cleanup-list', which is a list of clean-up symbols.  By default,
  494. `cc-mode' cleans up only the `scope-operator' construct, which is
  495. necessary for proper C++ support.  Note that clean-ups are only
  496. performed when the construct does not occur within a literal (see *Note
  497. Auto-newline insertion::), and when there is nothing but whitespace
  498. appearing between the individual components of the construct.
  499.    There are currently only five specific constructs that `cc-mode' can
  500. clean up, as indicated by these symbols:
  501.    * `brace-else-brace' - cleans up `} else {' constructs by placing
  502.      the entire construct on a single line.  Clean-up occurs when the
  503.      open brace after the `else' is typed.  So for example, this:
  504.           void spam(int i)
  505.           {
  506.               if( i==7 )
  507.               {
  508.                   dosomething();
  509.               }
  510.               else
  511.               {
  512.      appears like this after the open brace is typed:
  513.           void spam(int i)
  514.           {
  515.               if( i==7 ) {
  516.                   dosomething();
  517.               } else {
  518.    * `empty-defun-braces' - cleans up braces following a top-level
  519.      function or class definition that contains no body.  Clean up
  520.      occurs when the closing brace is typed.  Thus the following:
  521.           class Spam
  522.           {
  523.           }
  524.      is transformed into this when the close brace is typed:
  525.           class Spam
  526.           {}
  527.    * `defun-close-semi' - cleans up the terminating semi-colon on
  528.      top-level function or class definitions when they follow a close
  529.      brace. Clean up occurs when the semi-colon is typed.  So for
  530.      example, the following:
  531.           class Spam
  532.           {
  533.           }
  534.           ;
  535.      is transformed into this when the semi-colon is typed:
  536.           class Spam
  537.           {
  538.           };
  539.    * `list-close-comma' - cleans up commas following braces in array
  540.      and aggregate initializers.  Clean up occurs when the comma is
  541.      typed.
  542.    * `scope-operator' - cleans up double colons which may designate a
  543.      C++ scope operator split across multiple lines(1).  Clean up
  544.      occurs when the second colon is typed.  You will always want
  545.      `scope-operator' in the `c-cleanup-list' when you are editing C++
  546.      code.
  547.    ---------- Footnotes ----------
  548.    (1)  Certain C++ constructs introduce ambiguous situations, so
  549. `scope-operator' clean-ups may not always be correct.  This usually
  550. only occurs when scoped identifiers appear in switch label tags.
  551. File: ccmode,  Node: Hungry-deletion of whitespace,  Prev: Auto-newline insertion,  Up: Minor Modes
  552. Hungry-deletion of whitespace
  553. =============================
  554.    Hungry deletion of whitespace, or as it more commonly called,
  555. "hungry-delete mode", is a simple feature that some people find
  556. extremely useful.  In fact, you might find yourself wanting
  557. hungry-delete in *all* your editing modes!
  558.    In a nutshell, when hungry-delete mode is enabled, hitting the `DEL'
  559. character will consume all preceding whitespace, including newlines and
  560. tabs.  This can really cut down on the number of `DEL''s you have to
  561. type if, for example you made a mistake on the preceding line.
  562.    By default, `cc-mode' actually runs the command `c-electric-delete'
  563. when you hit `DEL'.  When this command is used to delete a single
  564. character (i.e. when it is called interactively with no numeric
  565. argument), it really runs the function contained in the variable
  566. `c-delete-function'.  This function is called with a single argument,
  567. which is the number of characters to delete.  `c-delete-function' is
  568. also called when the `DEL' key is typed inside a literal (see *Note
  569. Auto-newline insertion::.  Inside a literal, `c-electric-delete' is not
  570. electric, which is typical of all the so-called electric commands.
  571. File: ccmode,  Node: Indentation Commands,  Next: Customizing Indentation,  Prev: Minor Modes,  Up: Top
  572. Indentation Commands
  573. ********************
  574.    Various commands are provided which allow you to conveniently
  575. re-indent C constructs, and these are outlined below.  There are
  576. several things to note about these indentation commands.  First, when
  577. you change your programming style, either though `c-set-style' or some
  578. other means, your file does *not* automatically get re-indented.  When
  579. you change style parameters, you will typically need to reformat the
  580. line, expression, or buffer to see the effects of your changes.
  581.    Second, changing some variables have no effect on existing code, even
  582. when you do re-indent.  For example, the `c-hanging-*' variables and
  583. `c-cleanup-list' only affect newly entered code.  So for example,
  584. changing `c-hanging-braces-alist' and re-indenting the buffer will not
  585. adjust placement of braces already in the file.
  586.    Third, re-indenting large portions of code is currently rather
  587. inefficient.  Improvements have been made since previous releases of
  588. `cc-mode', and much more radical improvements will be made for the next
  589. release, but for now you need to be aware of this (1).  Some provision
  590. has been made to at least inform you as to the progress of your large
  591. re-indentation command.  The variable `c-progress-interval' controls
  592. how often a progress message is displayed.  Set this variable to `nil'
  593. to inhibit progress messages.  Note that this feature only works with
  594. Emacs 19.
  595.    Also, except as noted below, re-indentation is always driven by the
  596. same mechanisms that control on-the-fly indentation of code.  *Note New
  597. Indentation Engine:: for details.
  598.    To indent a single line of code, use `TAB' (`c-indent-command').
  599. The behavior of this command is controlled by the variable
  600. `c-tab-always-indent'.  When this variable is `t', `TAB' always just
  601. indents the current line.  When `nil', the line is indented only if
  602. point is at the left margin, or on or before the first non-whitespace
  603. character on the line, otherwise a real tab character is inserted.  If
  604. this variable's value is something other that `t' or `nil' (e.g.
  605. `'other'), then a real tab character is inserted only when point is
  606. inside a literal (see *Note Auto-newline insertion::), otherwise the
  607. line is indented.
  608.    To indent an entire balanced brace or parenthesis expression, use
  609. `M-C-q' (`c-indent-exp').  Note that point should be on the opening
  610. brace or parenthesis of the expression you want to indent.
  611.    Another very convenient keystroke is `C-c C-q' (`c-indent-defun')
  612. when re-indents the entire top-level function or class definition that
  613. encompasses point.  It leaves point at the same position within the
  614. buffer.
  615.    To indent any arbitrary region of code, use `M-C-\'
  616. (`indent-region').   This is a standard Emacs command, specially
  617. tailored for C code in a `cc-mode' buffer.  Note that of course, point
  618. and mark must delineate the region you want to indent.
  619.    While not strictly an indentation function, `M-C-h'
  620. (`c-mark-function') is useful for marking the current top-level
  621. function or class definition as the current region.
  622.    ---------- Footnotes ----------
  623.    (1)  In particular, I have had people complain about the speed that
  624. `cc-mode' re-indents `lex(1)' output.  Lex, yacc, and other code
  625. generators usually output some pretty perverse code.  *Don't* try to
  626. indent this stuff with `cc-mode'!
  627. File: ccmode,  Node: Customizing Indentation,  Next: Syntactic Symbols,  Prev: Indentation Commands,  Up: Top
  628. Customizing Indentation
  629. ***********************
  630.    The `c-offsets-alist' variable is where you customize all your
  631. indentations.  You simply need to decide what additional offset you want
  632. to add for every syntactic symbol.  You can use the command `C-c C-o'
  633. (`c-set-offset') as the way to set offsets, both interactively and from
  634. your mode hook.  Also, you can set up *styles* of indentation just like
  635. in BOCM.  Most likely, you'll find one of the pre-defined styles will
  636. suit your needs, but if not, this section will describe how to set up
  637. basic editing configurations.  *Note Styles:: for an explanation of how
  638. to set up named styles.
  639.    As mentioned previously, the variable `c-offsets-alist' is an
  640. association list between syntactic symbols and the offsets to be applied
  641. for those symbols.  In fact, these offset values can be an integer, a
  642. function or variable name, or one of the following symbols: `+', `-',
  643. `++', `--', `*', or `/'.  These symbols describe offset in multiples of
  644. the value of the variable `c-basic-offset'.  By defining a style's
  645. indentation in terms of this fundamental variable, you can change the
  646. amount of whitespace given to an indentation level while leaving the
  647. same relationship between levels.  Here are multiples of
  648. `c-basic-offset' that the special symbols correspond to:
  649.    * `+ ' =  `c-basic-offset' times 1
  650.    * `- ' =  `c-basic-offset' times -1
  651.    * `++' =  `c-basic-offset' times 2
  652.    * `--' =  `c-basic-offset' times -2
  653.    * `* ' =  `c-basic-offset' times 0.5
  654.    * `/ ' =  `c-basic-offset' times -0.5
  655. So, for example, because most of the default offsets are defined in
  656. terms of `+', `-', and `0', if you like the general indentation style,
  657. but you use 4 spaces instead of 2 spaces per level, you can probably
  658. achieve your style just by changing `c-basic-offset' like so (in your
  659. `.emacs' file)(1):
  660.      (setq-default c-basic-offset 4)
  661. This would change
  662.      int add( int val, int incr, int doit )
  663.      {
  664.          if( doit )
  665.              {
  666.                  return( val + incr );
  667.              }
  668.          return( val );
  669.      }
  670.      int add( int val, int incr, int doit )
  671.      {
  672.        if( doit )
  673.          {
  674.            return( val + incr );
  675.          }
  676.        return( val );
  677.      }
  678.    To change indentation styles more radically, you will want to change
  679. the value associated with the syntactic symbols in the
  680. `c-offsets-alist' variable.  First, I'll show you how to do that
  681. interactively, then I'll describe how to make changes to your `.emacs'
  682. file so that your changes are more permanent.
  683. * Menu:
  684. * Interactive Customization::
  685. * Permanent Customization::
  686. * Styles::
  687. * Advanced Customizations::
  688.    ---------- Footnotes ----------
  689.    (1)  The reason you need to use `setq-default' instead of `setq' is
  690. that `c-basic-offset' is a buffer local variable, as are most of the
  691. `cc-mode' configuration variables.  If you were to put this code in,
  692. e.g. your `c-mode-common-hook' function, you could use `setq'.
  693. File: ccmode,  Node: Interactive Customization,  Next: Permanent Customization,  Up: Customizing Indentation
  694. Interactive Customization
  695. =========================
  696.    As an example of how to customize indentation, let's change the
  697. style of example 2 above from:
  698.      1: int add( int val, int incr, int doit )
  699.      2: {
  700.      3:     if( doit )
  701.      4:         {
  702.      5:             return( val + incr );
  703.      6:         }
  704.      7:     return( val );
  705.      8: }
  706.      1: int add( int val, int incr, int doit )
  707.      2: {
  708.      3:     if( doit )
  709.      4:     {
  710.      5:         return( val + incr );
  711.      6:     }
  712.      7:     return( val );
  713.      8: }
  714.    In other words, we want to change the indentation of braces that
  715. open a block following a condition so that the braces line up under the
  716. conditional, instead of being indented.  Notice that the construct we
  717. want to change starts on line 4.  To change the indentation of a line,
  718. we need to see which syntactic component affect the offset calculations
  719. for that line.  Hitting `C-c C-s' on line 4 yields:
  720.      ((substatement-open . 46))
  721. so we know that to change the offset of the open brace, we need to
  722. change the indentation for the `substatement-open' syntactic symbol.
  723. To do this interactively, just hit `C-c C-o' (`c-set-offset').  This
  724. prompts you for the syntactic symbol to change, providing a reasonable
  725. default.  In this case, the default is `substatement-open', which is
  726. just the syntactic symbol we want to change!
  727.    After you hit return, `cc-mode' will then prompt you for the new
  728. offset value, with the old value as the default.  The default in this
  729. case is `+', so hit backspace to delete the `+', then hit `0' and
  730. `RET'.  This will associate the offset 0 with the syntactic symbol
  731. `substatement-open' in the `c-offsets-alist' variable.
  732.    To check your changes quickly, just hit `C-c C-q' (`c-indent-defun')
  733. to reindent the entire function.  The example should now look like:
  734.      1: int add( int val, int incr, int doit )
  735.      2: {
  736.      3:     if( doit )
  737.      4:     {
  738.      5:         return( val + incr );
  739.      6:     }
  740.      7:     return( val );
  741.      8: }
  742.    Notice how just changing the open brace offset on line 4 is all we
  743. needed to do.  Since the other affected lines are indented relative to
  744. line 4, they are automatically indented the way you'd expect.  For more
  745. complicated examples, this may not always work.  The general approach to
  746. take is to always start adjusting offsets for lines higher up in the
  747. file, then re-indent and see if any following lines need further
  748. adjustments.
  749. File: ccmode,  Node: Permanent Customization,  Next: Styles,  Prev: Interactive Customization,  Up: Customizing Indentation
  750. Permanent Indentation
  751. =====================
  752.    To make this change permanent, you need to add some lisp code to your
  753. `.emacs' file.  `cc-mode' provides four hooks that you can use to
  754. customize your language editing styles.  Four language specific hooks
  755. are provided, according to Emacs major mode conventions: `c-mode-hook',
  756. `c++-mode-hook', `objc-mode-hook', and `java-mode-hook'.  These get run
  757. as the last thing when you enter `c-mode', `c++-mode', `objc-mode', or
  758. `java-mode-hook' respectively.  `cc-mode' also provides a hook called
  759. `c-mode-common-hook' which is run by all three modes *before* the
  760. language specific hook.  Thus, to make changes consistently across all
  761. supported `cc-mode' modes, use `c-mode-common-hook'.  Most of the
  762. examples in this section will assume you are using the common hook.
  763.    Here's a simplified example of what you can add to your `.emacs'
  764. file to make the changes described in the previous section (*Note
  765. Interactive Customization::) more permanent.  See the Emacs manuals for
  766. more information on customizing Emacs via hooks.  *Note Sample .emacs
  767. File:: for a more complete sample `.emacs' file.  (1)
  768.      (defun my-c-mode-common-hook ()
  769.        ;; my customizations for all of c-mode, c++-mode, objc-mode, java-mode
  770.        (c-set-offset 'substatement-open 0)
  771.        ;; other customizations can go here
  772.        )
  773.      (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
  774.    For complex customizations, you will probably want to set up a
  775. *style* that groups all your customizations under a single name.
  776.    The offset value can also be a function, and this is how power users
  777. gain enormous flexibility in customizing indentation. *Note Advanced
  778. Customizations:: for details.
  779.    ---------- Footnotes ----------
  780.    (1)  The use of `add-hook' in this example only works for Emacs 19.
  781. Workarounds are available if you are using Emacs 18.
  782. File: ccmode,  Node: Styles,  Next: Advanced Customizations,  Prev: Permanent Customization,  Up: Customizing Indentation
  783. Styles
  784. ======
  785.    Most people only need to edit code formatted in just a few
  786. well-defined and consistent styles.  For example, their organization
  787. might impose a "blessed" style that all its programmers must conform
  788. to.  Similarly, people who work on GNU software will have to use the
  789. GNU coding style on C code.  Some shops are more lenient, allowing some
  790. variety of coding styles, and as programmers come and go, there could
  791. be a number of styles in use.  For this reason, `cc-mode' makes it
  792. convenient for you to set up logical groupings of customizations called
  793. "styles", associate a single name for any particular style, and pretty
  794. easily start editing new or existing code using these styles.  This
  795. chapter describes how to set up styles and how to edit your C code
  796. using styles.
  797. * Menu:
  798. * Built-in Styles::
  799. * Adding Styles::
  800. * File Styles::
  801. File: ccmode,  Node: Built-in Styles,  Next: Adding Styles,  Up: Styles
  802. Built-in Styles
  803. ---------------
  804.    If you're lucky, one of `cc-mode''s built-in styles might be just
  805. what you're looking for.  Some of the most common C and C++ styles are
  806. already built-in.  These include:
  807.    * `gnu' - coding style blessed by the Free Software Foundation for C
  808.      code in GNU programs.
  809.    * `k&r' - The classic Kernighan and Ritchie style for C code.
  810.    * `bsd' - *<TBD> Anybody know anything about the history of this
  811.      style?*
  812.    * `stroustrup' - The classic Stroustrup style for C++ code.
  813.    * `whitesmith' - *<TBD> Anybody know anything about the history of
  814.      this style?*
  815.    * `ellemtel' - Popular C++ coding standards as defined by
  816.      "Programming in C++, Rules and Recommendations", Erik Nyquist and
  817.      Mats Henricson, Ellemtel (1).
  818.    * `java' - The style for editing Java code.  Note that this style is
  819.      automatically installed when you enter `java-mode'.
  820.    * `CC-MODE' - Style that encapsulates the default values of the
  821.      `cc-mode' variables.  See below for details.
  822.    If you'd like to experiment with these built-in styles you can simply
  823. type the following in a `cc-mode' buffer:
  824.      `M-x c-set-style RET STYLE-NAME RET'
  825. Note that all style names are case insensitive, even the ones you
  826. define.
  827.    Setting a style in this way does *not* automatically re-indent your
  828. file.  For commands that you can use to view the effect of your changes,
  829. see *Note Indentation Commands::.
  830.    Once you find a built-in style you like, you can make the change
  831. permanent by adding a call to your `.emacs' file.  Let's say for
  832. example that you want to use the `ellemtel' style in all your files.
  833. You would add this:
  834.      (defun my-c-mode-common-hook ()
  835.        ;; use Ellemtel style for all C, C++, and Objective-C code
  836.        (c-set-style "ellemtel")
  837.        ;; other customizations can go here
  838.        )
  839.      (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
  840.    There is one other special style you can use, called `CC-MODE'.
  841. This is a style that is calculated by `cc-mode' when it starts up.  The
  842. `CC-MODE' style is also special because all other styles implicitly
  843. inherit from it; in other words, whenever you set a style, `cc-mode'
  844. first re-instates the `CC-MODE' style, then applies your new style
  845. configurations.
  846.    The `CC-MODE' style exists because once `cc-mode' initializes, it
  847. institutes the `gnu' style for compatibility with BOCM's defaults.  Any
  848. customizations you make in mode hooks will be based on the `gnu' style,
  849. unless you first do a `c-set-style' to `CC-MODE' or some other built-in
  850. style.
  851.    ---------- Footnotes ----------
  852.    (1)  This document is ftp'able from `euagate.eua.ericsson.se'
  853. File: ccmode,  Node: Adding Styles,  Next: File Styles,  Prev: Built-in Styles,  Up: Styles
  854. Adding Styles
  855. -------------
  856.    If none of the built-in styles is appropriate, you'll probably want
  857. to add a new style definition.  Styles are kept in the `c-style-alist'
  858. variable, but you probably won't want to modify this variable directly.
  859. `cc-mode' provides a function, called `c-add-style', that you can use
  860. to easily add new styles or update existing styles.  This function
  861. takes two arguments, a STYLENAME string, and an association list
  862. DESCRIPTION of style customizations.  If STYLENAME is not already in
  863. `c-style-alist', the new style is added, otherwise the style already
  864. associated with STYLENAME is changed to the new DESCRIPTION.  This
  865. function also takes an optional third argument, which if non-`nil',
  866. automatically institutes the new style in the current buffer.
  867.    The sample `.emacs' file provides a concrete example of how a new
  868. style can be added and automatically set.  *Note Sample .emacs File::.
  869. File: ccmode,  Node: File Styles,  Prev: Adding Styles,  Up: Styles
  870. File Styles
  871. -----------
  872.    The Emacs manual describes how you can customize certain variables
  873. on a per-file basis by including a "Local Variable" block at the end of
  874. the file.  So far, you've only seen a functional interface to
  875. `cc-mode', which is highly inconvenient for use in a Local Variable
  876. block.  `cc-mode' provides two variables that make it easier for you to
  877. customize your style on a per-file basis.
  878.    The variable `c-file-style' can be set to a style name string as
  879. described in *Note Built-in Styles::.  When the file is visited,
  880. `cc-mode' will automatically set the file's style to this style using
  881. `c-set-style'.
  882.    Another variable, `c-file-offsets', takes an association list
  883. similar to what is allowed in `c-offsets-alist'.  When the file is
  884. visited, `cc-mode' will automatically institute these offsets using
  885. `c-set-offset'.
  886.    Note that file style settings (i.e. `c-file-style') are applied
  887. before file offset settings (i.e. `c-file-offsets').
  888. File: ccmode,  Node: Advanced Customizations,  Prev: Styles,  Up: Customizing Indentation
  889. Advanced Customizations
  890. =======================
  891.    For most users, `cc-mode' will support their coding styles with very
  892. little need for customizations.  Usually, one of the standard styles
  893. defined in `c-style-alist' will do the trick.  At most, perhaps one of
  894. the syntactic symbol offsets will need to be tweaked slightly, or maybe
  895. `c-basic-offset' will need to be changed.  However, some styles require
  896. a more advanced ability for customization, and one of the real
  897. strengths of `cc-mode' is that the syntactic analysis model provides a
  898. very flexible framework for customizing indentation. This allows you to
  899. perform special indentation calculations for situations not handled by
  900. the mode directly.
  901. * Menu:
  902. * Custom Indentation Functions::
  903. * Custom Brace and Colon Hanging::
  904. * Customizing Semi-colons and Commas::
  905. * Other Special Indentations::
  906.